/**
 * 上传控制器
 * 处理文件上传相关的数据库操作
 */

import { BaseController, ensureDbInit, createResponse, createErrorResponse } from './BaseController'
import database from '../../utils/database'
import { generateId } from '../../mock/utils'

export class UploadController extends BaseController {
  constructor() {
    super('upload_files')
  }
  
  /**
   * 上传文件
   */
  async uploadFile(data: {
    fileName: string
    fileType: string
    fileSize: number
    filePath?: string
    category?: string
    description?: string
    tags?: string[]
  }) {
    try {
      await ensureDbInit()
      const fileId = generateId()
      const now = new Date().toISOString()
      
      // 模拟文件上传到服务器
      const uploadPath = `/uploads/${fileId}_${data.fileName}`
      const downloadUrl = `https://api.example.com/files/${fileId}/download`
      
      const fileData = {
        id: fileId,
        user_id: 'current_user',
        file_name: data.fileName,
        file_type: data.fileType,
        file_size: data.fileSize,
        file_path: uploadPath,
        download_url: downloadUrl,
        category: data.category || 'general',
        description: data.description || '',
        tags: JSON.stringify(data.tags || []),
        upload_status: 'completed',
        upload_progress: 100,
        created_at: now,
        updated_at: now,
        is_deleted: 0
      }
      
      await database.insert('upload_files', fileData)
      
      return createResponse({
        id: fileId,
        fileName: data.fileName,
        fileType: data.fileType,
        fileSize: data.fileSize,
        filePath: uploadPath,
        downloadUrl: downloadUrl,
        category: data.category || 'general',
        description: data.description || '',
        tags: data.tags || [],
        uploadStatus: 'completed',
        uploadProgress: 100,
        createdAt: now,
        updatedAt: now
      })
    } catch (error: any) {
      return createErrorResponse(error.message || '文件上传失败')
    }
  }
  
  /**
   * 获取文件列表
   */
  async getFiles(params: {
    page?: number
    pageSize?: number
    category?: string
    fileType?: string
    keyword?: string
  } = {}) {
    try {
      const {
        page = 1,
        pageSize = 20,
        category,
        fileType,
        keyword
      } = params
      
      let whereClause = 'user_id = ? AND is_deleted = 0'
      let whereParams: any[] = ['current_user']
      
      if (category) {
        whereClause += ' AND category = ?'
        whereParams.push(category)
      }
      
      if (fileType) {
        whereClause += ' AND file_type LIKE ?'
        whereParams.push(`${fileType}%`)
      }
      
      if (keyword) {
        whereClause += ' AND (file_name LIKE ? OR description LIKE ?)'
        whereParams.push(`%${keyword}%`, `%${keyword}%`)
      }
      
      const result = await database.paginate('upload_files', {
        page,
        pageSize,
        where: whereClause,
        whereParams,
        orderBy: 'created_at DESC'
      })
      
      if (result.code !== 0) {
        return createErrorResponse(result.message || '获取文件列表失败')
      }
      
      const paginationData = result.data || {}
      const list = (paginationData.list || []).map((item: any) => ({
        ...item,
        tags: item.tags ? JSON.parse(item.tags) : []
      }))
      
      return createResponse({
        list,
        page: paginationData.page,
        pageSize: paginationData.pageSize,
        total: paginationData.total
      })
    } catch (error: any) {
      return createErrorResponse(error.message || '获取文件列表失败')
    }
  }
  
  /**
   * 获取文件详情
   */
  async getFileDetail(id: string) {
    try {
      await ensureDbInit()
      const result = await database.query(
        'SELECT * FROM upload_files WHERE id = ? AND user_id = ? AND is_deleted = 0',
        [id, 'current_user']
      )
      
      if (result.code !== 0) {
        return createErrorResponse(result.message || '获取文件详情失败')
      }
      
      const data = result.data || []
      if (data.length === 0) {
        return createErrorResponse('文件不存在', 1003)
      }
      
      const file = data[0]
      return createResponse({
        ...file,
        tags: file.tags ? JSON.parse(file.tags) : []
      })
    } catch (error: any) {
      return createErrorResponse(error.message || '获取文件详情失败')
    }
  }
  
  /**
   * 更新文件信息
   */
  async updateFile(id: string, data: {
    fileName?: string
    category?: string
    description?: string
    tags?: string[]
  }) {
    try {
      await ensureDbInit()
      const updateData: any = {
        updated_at: new Date().toISOString()
      }
      
      if (data.fileName) {
        updateData.file_name = data.fileName
      }
      
      if (data.category) {
        updateData.category = data.category
      }
      
      if (data.description !== undefined) {
        updateData.description = data.description
      }
      
      if (data.tags) {
        updateData.tags = JSON.stringify(data.tags)
      }
      
      const rowsAffected = await database.update(
        'upload_files',
        updateData,
        'id = ? AND user_id = ? AND is_deleted = 0',
        [id, 'current_user']
      )
      
      if (rowsAffected === 0) {
        return createErrorResponse('文件不存在', 1003)
      }
      
      return createResponse({ success: true })
    } catch (error: any) {
      return createErrorResponse(error.message || '更新文件信息失败')
    }
  }
  
  /**
   * 删除文件
   */
  async deleteFile(id: string) {
    try {
      await ensureDbInit()
      const rowsAffected = await database.update(
        'upload_files',
        {
          is_deleted: 1,
          updated_at: new Date().toISOString()
        },
        'id = ? AND user_id = ? AND is_deleted = 0',
        [id, 'current_user']
      )
      
      if (rowsAffected === 0) {
        return createErrorResponse('文件不存在', 1003)
      }
      
      return createResponse({ success: true })
    } catch (error: any) {
      return createErrorResponse(error.message || '删除文件失败')
    }
  }
  
  /**
   * 获取文件下载链接
   */
  async getFileDownloadUrl(id: string) {
    try {
      await ensureDbInit()
      const result = await database.query(
        'SELECT download_url, file_name FROM upload_files WHERE id = ? AND user_id = ? AND is_deleted = 0',
        [id, 'current_user']
      )
      
      if (result.code !== 0) {
        return createErrorResponse(result.message || '获取下载链接失败')
      }
      
      const data = result.data || []
      if (data.length === 0) {
        return createErrorResponse('文件不存在', 1003)
      }
      
      const file = data[0]
      
      // 生成临时下载链接（模拟）
      const tempToken = generateId()
      const downloadUrl = `${file.download_url}?token=${tempToken}&expires=${Date.now() + 3600000}` // 1小时有效期
      
      return createResponse({
        downloadUrl: downloadUrl,
        fileName: file.file_name,
        expiresAt: new Date(Date.now() + 3600000).toISOString()
      })
    } catch (error: any) {
      return createErrorResponse(error.message || '获取下载链接失败')
    }
  }
  
  /**
   * 批量删除文件
   */
  async batchDeleteFiles(fileIds: string[]) {
    try {
      await ensureDbInit()
      
      if (!fileIds || fileIds.length === 0) {
        return createErrorResponse('请选择要删除的文件', 1001)
      }
      
      const now = new Date().toISOString()
      let successCount = 0
      
      for (const fileId of fileIds) {
        try {
          const rowsAffected = await database.update(
            'upload_files',
            {
              is_deleted: 1,
              updated_at: now
            },
            'id = ? AND user_id = ? AND is_deleted = 0',
            [fileId, 'current_user']
          )
          
          if (rowsAffected > 0) {
            successCount++
          }
        } catch (error) {
          // 单个删除失败不影响其他操作
          console.error(`删除文件 ${fileId} 失败:`, error)
        }
      }
      
      return createResponse({
        total: fileIds.length,
        success: successCount,
        failed: fileIds.length - successCount
      })
    } catch (error: any) {
      return createErrorResponse(error.message || '批量删除文件失败')
    }
  }
  
  /**
   * 获取文件分类统计
   */
  async getFileStats() {
    try {
      await ensureDbInit()
      
      // 按分类统计
      const categoryResult = await database.query(
        `SELECT 
          category,
          COUNT(*) as count,
          SUM(file_size) as totalSize
        FROM upload_files 
        WHERE user_id = ? AND is_deleted = 0
        GROUP BY category`,
        ['current_user']
      )
      
      if (categoryResult.code !== 0) {
        return createErrorResponse(categoryResult.message || '查询分类统计失败')
      }
      
      // 按文件类型统计
      const typeResult = await database.query(
        `SELECT 
          CASE 
            WHEN file_type LIKE 'image/%' THEN 'image'
            WHEN file_type LIKE 'video/%' THEN 'video'
            WHEN file_type LIKE 'audio/%' THEN 'audio'
            WHEN file_type LIKE 'application/pdf' THEN 'pdf'
            WHEN file_type LIKE 'text/%' THEN 'text'
            ELSE 'other'
          END as type,
          COUNT(*) as count,
          SUM(file_size) as totalSize
        FROM upload_files 
        WHERE user_id = ? AND is_deleted = 0
        GROUP BY type`,
        ['current_user']
      )
      
      if (typeResult.code !== 0) {
        return createErrorResponse(typeResult.message || '查询类型统计失败')
      }
      
      // 总体统计
      const totalResult = await database.query(
        `SELECT 
          COUNT(*) as totalFiles,
          SUM(file_size) as totalSize
        FROM upload_files 
        WHERE user_id = ? AND is_deleted = 0`,
        ['current_user']
      )
      
      if (totalResult.code !== 0) {
        return createErrorResponse(totalResult.message || '查询总体统计失败')
      }
      
      const categoryData = categoryResult.data || []
      const typeData = typeResult.data || []
      const totalData = totalResult.data || []
      
      const total = totalData[0] || { totalFiles: 0, totalSize: 0 }
      
      return createResponse({
        totalFiles: total.totalFiles,
        totalSize: total.totalSize,
        categoryStats: categoryData,
        typeStats: typeData
      })
    } catch (error: any) {
      return createErrorResponse(error.message || '获取文件统计失败')
    }
  }
  
  /**
   * 搜索文件
   */
  async searchFiles(params: {
    keyword: string
    page?: number
    pageSize?: number
    category?: string
    fileType?: string
  }) {
    try {
      const { keyword, page = 1, pageSize = 20, category, fileType } = params
      
      if (!keyword || keyword.trim() === '') {
        return createErrorResponse('搜索关键词不能为空', 1001)
      }
      
      let whereClause = 'user_id = ? AND is_deleted = 0 AND (file_name LIKE ? OR description LIKE ?)'
      let whereParams: any[] = ['current_user', `%${keyword}%`, `%${keyword}%`]
      
      if (category) {
        whereClause += ' AND category = ?'
        whereParams.push(category)
      }
      
      if (fileType) {
        whereClause += ' AND file_type LIKE ?'
        whereParams.push(`${fileType}%`)
      }
      
      const result = await database.paginate('upload_files', {
        page,
        pageSize,
        where: whereClause,
        whereParams,
        orderBy: 'created_at DESC'
      })
      
      if (result.code !== 0) {
        return createErrorResponse(result.message || '搜索文件失败')
      }
      
      const paginationData = result.data || {}
      const list = (paginationData.list || []).map((item: any) => ({
        ...item,
        tags: item.tags ? JSON.parse(item.tags) : []
      }))
      
      return createResponse({
        list,
        page: paginationData.page,
        pageSize: paginationData.pageSize,
        total: paginationData.total
      })
    } catch (error: any) {
      return createErrorResponse(error.message || '搜索文件失败')
    }
  }
  
  /**
   * 获取最近上传的文件
   */
  async getRecentFiles(limit: number = 10) {
    try {
      await ensureDbInit()
      const result = await database.query(
        `SELECT * FROM upload_files 
        WHERE user_id = ? AND is_deleted = 0 
        ORDER BY created_at DESC 
        LIMIT ?`,
        ['current_user', limit]
      )
      
      if (result.code !== 0) {
        return createErrorResponse(result.message || '获取最近文件失败')
      }
      
      const data = result.data || []
      const files = data.map((item: any) => ({
        ...item,
        tags: item.tags ? JSON.parse(item.tags) : []
      }))
      
      return createResponse(files)
    } catch (error: any) {
      return createErrorResponse(error.message || '获取最近文件失败')
    }
  }
  
  /**
   * 清理过期文件
   */
  async cleanupExpiredFiles(daysOld: number = 30) {
    try {
      await ensureDbInit()
      const cutoffDate = new Date()
      cutoffDate.setDate(cutoffDate.getDate() - daysOld)
      const cutoffDateString = cutoffDate.toISOString()
      
      const result = await database.query(
        'SELECT COUNT(*) as count FROM upload_files WHERE user_id = ? AND is_deleted = 1 AND updated_at < ?',
        ['current_user', cutoffDateString]
      )
      
      if (result.code !== 0) {
        return createErrorResponse(result.message || '查询过期文件失败')
      }
      
      const countData = result.data || []
      const expiredCount = (countData[0] && typeof countData[0].count !== 'undefined') ? countData[0].count : 0
      
      if (expiredCount > 0) {
        // 物理删除过期文件记录
        await database.executeSql(
          'DELETE FROM upload_files WHERE user_id = ? AND is_deleted = 1 AND updated_at < ?',
          ['current_user', cutoffDateString]
        )
      }
      
      return createResponse({
        cleanedCount: expiredCount
      })
    } catch (error: any) {
      return createErrorResponse(error.message || '清理过期文件失败')
    }
  }
}

// 导出单例实例
export const uploadController = new UploadController()